#include "ServerController.h"


ServerController::ServerController(Model *m, View *v, NetworkPat* net): Controller(m, v)
{
  _model = (ServerModel*)m;
  _view = (ServerView*)v;
  _net = net;
  newGameState = GameState::ServerPlay;
  mShouldReset = true;
}

ServerController::~ServerController(void)
{
}

void ServerController::HandleMessages(std::list<Message*> *l)
{
  if(l == NULL)
    return;
  //get messages from the network
  if(mShouldReset)
  {
    mShouldReset = false;
  }
  std::list<Message*>* l2 = _net->Recv();

  newGameState = GameState::ServerPlay;
  while(!l2->empty())
  {
    Message* temp = l2->front();
    l2->pop_front();
    if(temp->GetMessageType() == MessageType::SYSTEM)
    {
      switch(temp->GetMessageContent())
      {
        case NetMessage::LEAVE:
          //deal with a player leaving
          
          break;
        case NetMessage::JOIN:
          //deal with a player joining
          break;
        case NetMessage::WIN:
          //somebody won the game, time to tell everyone that the game is over
          int winner = temp->GetMessageId();
          for(unsigned int i = 0; i < _net->GetCount(); ++i)
          {
            Message* endGame;
            if((i + 1) == winner)
            {
              endGame = new Message(MessageType::SYSTEM, NetMessage::WIN);
            }
            else
            {
              endGame = new Message(MessageType::SYSTEM, NetMessage::LOSE);
            }
            _net->SendToOne(endGame, i);
          }
          mShouldReset = true;
          newGameState = GameState::MainMenu;
          break;
      }
    }
    else
    {
      this->_net->Send(temp);
    }
  }
}

GameState ServerController::Update(void)
{
  _view->DrawScreen();
  return newGameState;
}

void ServerController::PassMessage(Message* msg)
{
}

void ServerController::ProcessMessages(void)
{
}
